<?php

namespace App\Services;

use App\Models\HallPartnerConfig;
use App\Models\OrderRepairRecord;
use App\Models\Partner;
use App\Models\PartnerConfig;
use App\Models\PartnerHot;
use common\enum\CommonEnum;
use common\enum\MasterLogEnum;
use common\utils\SysCode;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class PartnerService
{
    const API_NUM = 1;
    static $gameType = [
        CommonEnum::GAME_EGAME => '电子',
        CommonEnum::GAME_LIVE => '视讯',
        CommonEnum::GAME_SPORT => '体育',
        CommonEnum::GAME_ESPORT => '电竞',
        CommonEnum::GAME_CARD => '棋牌',
        CommonEnum::GAME_LOTTERY => '彩票',
    ];

    //获取当前厅开启的第三方api
    public static function getHallOpenPartner($hall_id, $params = [])
    {

        //获取当前厅开启的API
        $obj = HallPartnerConfig::where('hall_id', $hall_id)
            ->orderBy('sort', 'ASC');
        if (isset($params['game_type'])) $obj->where('game_type', $params['game_type']);
        if (isset($params['partner_name'])) $obj->where('partner_name', $params['partner_name']);
        if (isset($params['partner_id'])) $obj->where('partner_id', $params['partner_id']);
        return $obj->get()->toArray();
    }

    // 查找游戏的种类
    public static function getPartner($gameType = 0)
    {
        $query = PartnerConfig::select(['partner_id as id', 'partner_name as name']);
        if (!empty($gameType)) {
            $query->where(['game_type' => $gameType]);
        }
        return $query->groupBy('partner_id')->get();
    }

    public static function getPartnerSetting($id)
    {
        $hp = Partner::where(['id' => $id])->first();
        if ($hp) {
            return json_decode($hp['config'], true);
        }
        return [];
    }

    public static function updatePartnerSetting($id, $config)
    {
        return Partner::where(['id' => $id])->update(['config' => $config]);
    }

    public static function getPartnerConfig()
    {
        return PartnerConfig::all();
    }

    public static function updatePartnerConfig($id, $attrs)
    {
        $pc = PartnerConfig::where(['id' => $id])->first();
        if (empty($pc) || empty($attrs)) {
            return error_exit(SysCode::INVALID_ARGUMENT);
        }
        DB::beginTransaction();
        try {
            $updateObj = HallPartnerConfig::where(["partner_id" => $pc["partner_id"], "game_type" => $pc["game_type"]])->whereIn('status', [CommonEnum::ENABLED, CommonEnum::DISABLE]);
            $recoverObj = HallPartnerConfig::where(["partner_id" => $pc["partner_id"], "game_type" => $pc["game_type"]])->whereIn('pre_status', [CommonEnum::ENABLED, CommonEnum::DISABLE]);

            // 操作status
            if (isset($attrs['status'])) {
                $status = $attrs['status'] ? CommonEnum::ENABLED : CommonEnum::DISABLE;
                if ($status == CommonEnum::ENABLED) {
                    // 启用，还原配置
                    $recoverObj->update(['status' => DB::raw('pre_status')]);
                } elseif ($status == CommonEnum::DISABLE) {
                    // 禁用，备份配置
                    $updateObj->update(['pre_status' => DB::raw('status')]);
                    $updateObj->update(['status' => CommonEnum::DELETE]);
                }
            }
            // 操作maintain 
            if (isset($attrs['maintaining'])) {
                $updateObj->update(['maintaining' => $attrs['maintaining']]);
            }

            PartnerConfig::where(['id' => $id])->update($attrs);
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            dd($e->getMessage());
            Log::error('UpdatePartnerConfig Error');
            return error_exit(SysCode::INTERNAL_SERVER_ERROR);
        }
        //操作status写日志
        if (!empty($attrs['status']) || isset($attrs['status'])) {
            $remark = str_replace(['{:type}', '{:game_type}', '{:game_name}'],
                [MasterLogEnum::STATUS[$attrs['status']], CommonEnum::GAME_SUFFIX[$pc['game_type']], $pc['partner_name']],
                MasterLogEnum::REMARK['game_switch']);
            MasterLogService::writeMasterLog(MasterLogEnum::GAME_SWITCH_EDIT, MasterLogEnum::SUCCESS, $remark);
        }
        return [];
    }

    public static function getHotSettingList($gameType)
    {
        $query = PartnerConfig::select([
            'id',
            'partner_name',
            'game_type',
        ])->orderBy('sort')->orderBy('id');

        if (empty($gameType)) {
            $query->addSelect([
                'top_hot as is_hot',
                'top_sort as sort'
            ]);
        } else {
            $query->addSelect([
                'is_hot',
                'sort'
            ])->where(['game_type' => $gameType]);
        }
        return $query->get();
    }

    public static function updateHotSetting($gameType, $list)
    {
        if (empty($list)) {
            return error_exit(SysCode::INVALID_ARGUMENT);
        }
        $hotKey = 'is_hot';
        $sortKey = 'sort';
        if (empty($gameType)) {
            $hotKey = 'top_hot';
            $sortKey = 'top_sort';
        }
        $data   = [];
        $isSortUpdate = count($list)>self::API_NUM ? true : false;
        foreach ($list as $l) {
            if($isSortUpdate){
                $pc = PartnerConfig::where(['id' => $l['id']])->first();
                $key  = $pc['partner_name'] . CommonEnum::GAME_SUFFIX[$pc['game_type']];
                $data['old'][$key] = $pc['sort'];
                if (empty($gameType)) {
                    $data['old'][$key] = $pc['top_sort'];
                }
            }
            if (isset($l['id']) && isset($l['is_hot']) && isset($l['sort'])) {
                PartnerConfig::where(['id' => $l['id']])->update([$hotKey => $l['is_hot'], $sortKey => $l['sort']]);
            } else {
                return error_exit(SysCode::INVALID_ARGUMENT);
            }
        }
        //热门开关写日志
        $remark    = MasterLogEnum::REMARK['game_hot_sort'];// 排序
        $hotRemark = MasterLogEnum::REMARK['game_hot_switch'];// 开关
        if (empty($gameType)) {
            $remark    = MasterLogEnum::REMARK['game_top_sort'];// 排序
            $hotRemark = MasterLogEnum::REMARK['game_top_hot'];// 开关
        }
        foreach ($list as $l) {
            $pc        = PartnerConfig::where(['id' => $l['id']])->first();
            if(!$isSortUpdate) {
                if (isset($l['is_hot'])) {
                    $status    = $l['is_hot'] ? CommonEnum::ENABLED : CommonEnum::DISABLE;
                    $hotRemark = str_replace(['{:type}', '{:game_type}', '{:game_name}'],
                            [MasterLogEnum::STATUS[$status], CommonEnum::GAME_SUFFIX[$pc['game_type']],$pc['partner_name']], $hotRemark);
                    MasterLogService::writeMasterLog(MasterLogEnum::GAME_IS_HOT, MasterLogEnum::SUCCESS, $hotRemark);
                }
            }
            if ($isSortUpdate) {
                if (isset($l['sort'])) {
                    $key  = $pc['partner_name'] . CommonEnum::GAME_SUFFIX[$pc['game_type']];
                    $data['new'][$key] = $l['sort'];
                    if (!empty($gameType)) {
                        $remark = str_replace('{:type}', CommonEnum::GAME_SUFFIX[$pc['game_type']], $remark);
                    }
                }
            }
        }
        if ($isSortUpdate) {
            MasterLogService::writeMasterLog(MasterLogEnum::GAME_SORT, MasterLogEnum::SUCCESS, $remark, $data);
        }
        return [];
    }

    public static function getPartnerConfigList($type)
    {
        $data = PartnerConfig::select('partner_id', 'partner_name', 'game_type');
        if (!empty($type) && in_array($type, [CommonEnum::GAME_EGAME, CommonEnum::GAME_LIVE, CommonEnum::GAME_SPORT, CommonEnum::GAME_ESPORT, CommonEnum::GAME_LOTTERY, CommonEnum::GAME_CARD])) {
            $data = $data->where(['game_type' => $type]);
        }
        return $data->get();
    }
    //获取第三方列表及补单状态
    public static function getRepairList()
    {
        $list = PartnerConfig::select(['partner_id', 'partner_name', 'game_type'])->get()->toArray();
        $games = [];
        foreach ($list as $game) {
            $data = self::isRepair($game['partner_name']);
            if ($game['game_type'] == CommonEnum::GAME_EGAME) {
                $games['egame'][] = [
                    'game_id' => $game['partner_id'],
                    'game_name' => "{$game['partner_name']}" . self::$gameType[$game['game_type']],
                    'game_type' => 'egame',
                    'is_repair' => $data['is_repair'],
                    'begin_time' => $data['begin_time'],
                    'end_time' => $data['end_time'],
                ];
            } elseif ($game['game_type'] == CommonEnum::GAME_LIVE) {
                $games['live'][] = [
                    'game_id' => $game['partner_id'],
                    'game_name' => "{$game['partner_name']}" . self::$gameType[$game['game_type']],
                    'game_type' => 'live',
                    'is_repair' => $data['is_repair'],
                    'begin_time' => $data['begin_time'],
                    'end_time' => $data['end_time'],
                ];
            } elseif ($game['game_type'] == CommonEnum::GAME_SPORT) {
                $games['sport'][] = [
                    'game_id' => $game['partner_id'],
                    'game_name' => "{$game['partner_name']}" . self::$gameType[$game['game_type']],
                    'game_type' => 'sport',
                    'is_repair' => $data['is_repair'],
                    'begin_time' => $data['begin_time'],
                    'end_time' => $data['end_time'],
                ];
            } elseif ($game['game_type'] == CommonEnum::GAME_ESPORT) {
                $games['esport'][] = [
                    'game_id' => $game['partner_id'],
                    'game_name' => "{$game['partner_name']}" . self::$gameType[$game['game_type']],
                    'game_type' => 'esport',
                    'is_repair' => $data['is_repair'],
                    'begin_time' => $data['begin_time'],
                    'end_time' => $data['end_time'],
                ];
            } elseif ($game['game_type'] == CommonEnum::GAME_CARD) {
                $games['card'][] = [
                    'game_id' => $game['partner_id'],
                    'game_name' => "{$game['partner_name']}" . self::$gameType[$game['game_type']],
                    'game_type' => 'card',
                    'is_repair' => $data['is_repair'],
                    'begin_time' => $data['begin_time'],
                    'end_time' => $data['end_time'],
                ];
            } elseif ($game['game_type'] == CommonEnum::GAME_LOTTERY) {
                $games['lottery'][] = [
                    'game_id' => $game['partner_id'],
                    'game_name' => "{$game['partner_name']}" . self::$gameType[$game['game_type']],
                    'game_type' => 'lottery',
                    'is_repair' => $data['is_repair'],
                    'begin_time' => $data['begin_time'],
                    'end_time' => $data['end_time'],
                ];
            }
        }
        return $games;
    }

    public static function getPartnerById($id)
    {
        return Partner::where(['id' => $id])->select(['id', 'name'])->get()->toArray();
    }

    //是否在补单中
    public static function isRepair($partner_name)
    {

        $repairInfo = OrderRepairRecord::where(['status' => CommonEnum::ENABLED, 'partner_name' => $partner_name])->get()->toArray();

        $data = [
            'is_repair' => $repairInfo?1:0,
            'begin_time' => $repairInfo[0]['begin_time'] ?? '',
            'end_time' => $repairInfo[0]['end_time'] ?? '',
        ];
        return $data;
    }

    //获取第三方列表
    public static function getPartnerList()
    {
        $list = PartnerConfig::select(['partner_id', 'partner_name', 'game_type'])->get()->toArray();
        $games = [];
        foreach ($list as $game) {
            $games[$game['game_type']][] = [
                'game_id' => $game['partner_id'],
                'game_name' => "{$game['partner_name']}" . self::$gameType[$game['game_type']],
                'game_type' => $game['game_type']
            ];
        }
        return $games;
    }

    /**
     * 设置维护时间
     * @param $arrts
     * @return array
     * @throws \App\Exceptions\CustomException
     */
    public static function setMaintainTime($arrts)
    {
        if (!empty($arrts['end_time']) && !empty($arrts['start_time'])) {
            if (strtotime($arrts['start_time']) < time() && time() < strtotime($arrts['end_time'])) {//开始时间大于结束时间
                $arrts['maintaining'] = CommonEnum::ENABLED;
            } else {
                $arrts['maintaining'] = CommonEnum::DISABLE;
            }
        }else{//时间为空maintaining维护开关直接关闭
            $arrts['maintaining'] = CommonEnum::DISABLE;
        }

        DB::beginTransaction();
        try {
            PartnerConfig::where(["partner_id" => $arrts['partner_id'], 'game_type' => $arrts['game_type']])->update($arrts);
            HallPartnerConfig::where(["partner_id" => $arrts["partner_id"], "game_type" => $arrts["game_type"]])->update(['maintaining' => $arrts['maintaining']]);
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            Log::error('UpdatePartnerConfig||PartnerConfig Error');
            error_exit(SysCode::INTERNAL_SERVER_ERROR);
        }
        //日志写入
        $games = PartnerConfig::where(["partner_id" => $arrts['partner_id'], 'game_type' => $arrts['game_type']])->first();
        $remark = str_replace(['{:game_type}', '{:game_name}', '{:star_time}', '{:end_time}'],
            [CommonEnum::GAME_SUFFIX[$games['game_type']], $games['partner_name'], $arrts['start_time'], $arrts['end_time']],
            MasterLogEnum::REMARK['game_maintain_time']);
        MasterLogService::writeMasterLog(MasterLogEnum::GAME_MAINTAIN_TIME, MasterLogEnum::SUCCESS,$remark);
        return [];
    }

}
